import os

from PyQt5.QtWidgets import QWidget, QPushButton, QLabel, QLineEdit, QGridLayout, QFileDialog, \
    QHBoxLayout, QVBoxLayout, QMessageBox

import LeftTabWidget
import util
from PrintSet import PrintSetWidget
from Qprogress import RoundProgress

ROOT_DIR = 'root_dir'
TARGET_DIR = 'target_dir'


class ChooseDirWidget(QWidget):

    def __init__(self):
        super(ChooseDirWidget, self).__init__()
        self.pg_bar = None
        self.print_widget = None
        self.cwd = os.getcwd()  # 获取当前程序文件位置
        self.init_ui()

    def init_ui(self):
        # root dir

        self.rootdir_label = QLabel('根目录')
        self.rootdir_edit = QLineEdit()
        self.btn_choose_root_dir = QPushButton(self)
        self.btn_choose_root_dir.setObjectName("btn_chooseDir")
        self.btn_choose_root_dir.setText("选择根文件夹")
        self.btn_choose_root_dir.setToolTip("存放.xlsx（excel文件格式）文件的文件夹")

        # choose target
        self.tarfile_label = QLabel('目标文件')
        self.tarfile_edit = QLineEdit()
        self.btn_target_dir = QPushButton(self)
        self.btn_target_dir.setObjectName("btn_tarDir")
        self.btn_target_dir.setText("选择输出文件夹")
        self.btn_target_dir.setToolTip("输出合并后xlsx（excel文件格式）文件的文件夹")
        # 设置布局

        self.generate_file_lb = QLabel('合并文件')
        self.generate_file_edit = QLineEdit()
        self.generate_file_edit.setReadOnly(True)

        self.btn_print_set = QPushButton('打印设置')
        self.btn_print_set.setObjectName('btn_print_set')
        self.btn_result_file_open = QPushButton('打开合并文件')
        self.btn_result_dir_open = QPushButton('打开目标文件夹')
        gridLayout = QGridLayout()
        gridLayout.setSpacing(10)
        gridLayout.addWidget(self.rootdir_label, 1, 0)
        gridLayout.addWidget(self.rootdir_edit, 1, 1)
        gridLayout.addWidget(self.btn_choose_root_dir, 1, 2)
        gridLayout.addWidget(self.tarfile_label, 2, 0)
        gridLayout.addWidget(self.tarfile_edit, 2, 1)
        gridLayout.addWidget(self.btn_target_dir, 2, 2)
        gridLayout.addWidget(self.btn_print_set, 3, 2)
        gridLayout.addWidget(self.generate_file_lb, 4, 0, 1, 1)
        gridLayout.addWidget(self.generate_file_edit, 4, 1, 1, 2)
        gridLayout.addWidget(self.btn_result_file_open, 5, 0, 1, 2)
        gridLayout.addWidget(self.btn_result_dir_open, 5, 2, 1, 2)
        vbox_layout = QVBoxLayout()
        hlayout = QHBoxLayout()

        # hlayout.addWidget(self.btn_result_file_open)
        # hlayout.addWidget(self.btn_result_dir_open)
        self.btn_result_file_open.setEnabled(False)
        self.btn_result_dir_open.setEnabled(False)
        self.pg_bar = RoundProgress()
        vbox_layout.addLayout(gridLayout)
        vbox_layout.addWidget(self.pg_bar)
        # vbox_layout.addLayout(hlayout)

        self.setLayout(vbox_layout)
        # self.pg_bar = QProgressBar()
        # gridLayout.addWidget(self.pg_bar, 5, 0, 1, 2)

        # 当textedit改变时，保存配置

        self.rootdir_edit.textChanged.connect(lambda: self.save_config({ROOT_DIR: self.rootdir_edit.text()}))
        self.rootdir_edit.textChanged.connect(self.disable_job_finished_widget)
        self.tarfile_edit.textChanged.connect(lambda: self.save_config({TARGET_DIR: self.tarfile_edit.text()}))
        self.tarfile_edit.textChanged.connect(self.disable_job_finished_widget)

        # 设置信号
        # 三个文件选择按钮
        self.btn_choose_root_dir.clicked.connect(self.choose_dir)
        self.btn_target_dir.clicked.connect(self.choose_dir)

        # 打印设置点击
        self.btn_print_set.clicked.connect(self.show_print_widget)
        # 任务完成后显示
        self.btn_result_file_open.clicked.connect(self.slot_btn_fileopen)
        self.btn_result_dir_open.clicked.connect(self.slot_btn_tar_dir_open)

        # 读取上次配置
        self.load_config()

    def load_config(self):
        last_root_dir = util.get_config(ROOT_DIR)
        last_target_dir = util.get_config(TARGET_DIR)
        self.rootdir_edit.setText(last_root_dir)
        self.tarfile_edit.setText(last_target_dir)

    @staticmethod
    def save_config(cfg: dict):
        util.write_config(cfg)

    def slot_btn_tar_dir_open(self):
        dir_name = os.path.dirname(self.generate_file_edit.text())
        util.my_logger.debug('Target file dir : ' + dir_name)
        os.startfile(dir_name)
        # os.open(os.path.dirname(self.tarfile_edit.text()))

    def show_print_widget(self):
        self.print_widget = PrintSetWidget()
        self.print_widget.show()

    def choose_dir(self):
        dir_choose = QFileDialog.getExistingDirectory(self,
                                                      "选取文件夹",
                                                      self.cwd)  # 起始路径

        if dir_choose == "":
            util.my_logger.debug("\n取消选择")
            return
        sender = self.sender()
        if sender == self.btn_choose_root_dir:
            self.rootdir_edit.setText(dir_choose.replace('/', os.sep))
            util.my_logger.debug("你选择的文件夹为:{}".format(self.rootdir_edit.text()))
        elif sender == self.btn_target_dir:
            self.tarfile_edit.setText(dir_choose.replace('/', os.sep))
            util.my_logger.debug("你选择的文件夹为:{}".format(self.tarfile_edit.text()))

    def slot_btn_fileopen(self):
        os.startfile(self.generate_file_edit.text())

    def show_job_finished_widget(self):
        self.btn_result_dir_open.setEnabled(True)
        self.btn_result_file_open.setEnabled(True)

    def disable_job_finished_widget(self):
        self.btn_result_dir_open.setEnabled(False)
        self.btn_result_file_open.setEnabled(False)

    def show_message(self, message):
        QMessageBox.information(self, "Warning", message,
                                QMessageBox.Yes)
